//
//  SSHomeViewController.swift
//  SSSina
//
//  Created by ss on 2017/6/28.
//  Copyright © 2017年 ss. All rights reserved.
//

import UIKit
import YYModel

//cell 可重用标识
private let homeCELLID = "homeCELLID"


class SSHomeViewController: SSBaseViewController {

    //创建全局的viewModel
    fileprivate lazy var homeViewModle: SSHomeViewModel = SSHomeViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //如果用户没有登陆 设置信息
        if !isLogin {
            visitorView?.setupVisitorViewInfo(imgName: nil, title: nil)
            //要加return否则 accesstoken为Nil 之后就会请求不到数据
            return
        }

        setupUI()
        loadData()
        
    }
    //设置tableview的相关信息
    private func setupTableViewInfo(){
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(SSHomeCell.self, forCellReuseIdentifier:homeCELLID )
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 300
        //分割线样式
        tableView.separatorStyle = .none
        //设置footView
        tableView.tableFooterView = footView
        
        //添加刷新控件
        tableView.addSubview(refreshControl)
    }
    
    
    
    //设置视图
    private func setupUI(){
        navigationController?.view.insertSubview(pulldownTipLabel, belowSubview: navigationController!.navigationBar)
        setupNav()
        setupTableViewInfo()
    }
    
    private func setupNav(){
        // 左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", title: nil, target: self, action: #selector(leftBarBtnClick))
        // 右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", title: nil, target: self, action: #selector(rightBarBtnClick))
    }
    
    //懒加载控件
    //自定义上拉刷新加载更多
    fileprivate lazy var footView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        //颜色
        view.color = SSThemeColor
        return view
    }()
    
    //系统的下拉刷新控件
    fileprivate lazy var refreshControl:SSRefreshControll = {
        let view = SSRefreshControll()
        view.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
        return view
    }()
    
    
    //刷新微博指示器
    fileprivate lazy var pulldownTipLabel:UILabel = {
        let lab = UILabel(frame: CGRect(x: 0, y: 64 - 30, width: SSSCREENW, height: 30))
        lab.backgroundColor = SSThemeColor
        lab.font = UIFont.systemFont(ofSize: SSNormalFontSize)
        lab.textColor = UIColor.white
        lab.textAlignment = .center
        lab.isHidden = true
        return lab
    }()

}

// 请求首页数据
extension SSHomeViewController{
    func loadData(){
        
        homeViewModle.getHomeData(isPullUp: self.footView.isAnimating) { (isFinish, count) in
            
            // 判断
            if !isFinish{
                print("请求失败")
                return
            }else{
                // 判断是否是首次请求数据 或者是下拉刷新
                if !self.footView.isAnimating{
                    self.setupPulldownTipLabelAnim(count: count)
                }
                self.tableView.reloadData()
            }
            self.endRefreshing()
        }
        
    }
    
    // 设置pulldownTipLabel的动画
    // 只有第一次和下拉刷新中设置动画
    fileprivate func setupPulldownTipLabelAnim(count: Int){
        
        // 判断是否显示
        if !self.pulldownTipLabel.isHidden {
            return
        }
        
        self.pulldownTipLabel.isHidden = false
        
        // 记录描述文字
        let text: String
        if count > 0 {
            text = "您更新了\(count)条微博"
        }else{
            text = "您已经是最新的微博数据拉"
        }
        // 赋值
        pulldownTipLabel.text = text
        
        // 设置动画
        UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
            self.pulldownTipLabel.transform = CGAffineTransform(translationX: 0, y: 30)
        }) { (_) in
            UIView.animate(withDuration: 1, animations: {
                self.pulldownTipLabel.transform = CGAffineTransform.identity
            }, completion: { (_) in
                // 隐藏
                self.pulldownTipLabel.isHidden = true
            })
        }
    }
    
    
    // 监听下拉刷新开始请求数据
    @objc fileprivate func refreshAction(){
        print("刷新数据")
        loadData()
    }
    
    fileprivate func endRefreshing(){
        // 停止动画
        self.footView.stopAnimating()
        self.refreshControl.endRefresh()
    }
}

//数据源方法
extension SSHomeViewController: UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModle.dataList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "homeCELLID", for: indexPath) as! SSHomeCell
        //赋值
        cell.statusViewModel = homeViewModle.dataList[indexPath.row]
        cell.selectionStyle = .none
        return cell
        
    }
    // 将要显示的cell
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 如果到最后一行 就应该开始footerView的动画
        // footerView.isAnimating是否在执行动画
        if indexPath.row == homeViewModle.dataList.count - 1 && !self.footView.isAnimating {
            print(indexPath.row, "行数")
            // 执行动画
            self.footView.startAnimating()
            // 发送网络请求
            loadData()
            
        }
    }
    
}

//监听事件
extension SSHomeViewController{
    
    //点击左侧按钮
    @objc fileprivate func leftBarBtnClick(){
        print("点击左侧按钮")
    }
    //点击右侧按钮
    @objc fileprivate func rightBarBtnClick(){
        print("点击右侧按钮")
        let temVC = SSTempViewController()
        
        navigationController?.pushViewController(temVC, animated:true)
    }
}

